package com.acme.superduperapp;

import com.codename1.components.MultiButton;
import com.codename1.components.ScaleImageLabel;
import com.codename1.components.SpanButton;
import com.codename1.components.SpanLabel;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.JSONParser;
import static com.codename1.ui.CN.*;
import com.codename1.io.Log;
import com.codename1.ui.Button;
import com.codename1.ui.Display;
import com.codename1.ui.FontImage;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.layouts.LayeredLayout;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.ui.util.UITimer;
import java.io.IOException;
import com.codename1.ui.Toolbar;
import com.codename1.io.NetworkEvent;
import com.codename1.io.NetworkManager;
import com.codename1.ui.ButtonGroup;
import com.codename1.ui.Command;
import com.codename1.ui.Component;
import static com.codename1.ui.Component.BOTTOM;
import com.codename1.ui.Container;
import com.codename1.ui.EncodedImage;
import com.codename1.ui.Image;
import com.codename1.ui.InfiniteContainer;
import com.codename1.ui.RadioButton;
import com.codename1.ui.Tabs;
import com.codename1.ui.URLImage;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.layouts.GridLayout;
import com.codename1.ui.plaf.DefaultLookAndFeel;
import com.codename1.ui.plaf.Style;
import com.codename1.ui.table.TableLayout;
import com.codename1.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename
 * One</a> for the purpose of building native mobile applications using Java.
 */
public class MyApplication {
    
    public Form current;
    public static  Resources theme;
    
    public static Tabs tabs;
    
    public Container tabsFlow;
    
    public boolean hiddenTabs = false;
    
    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);
        
        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);
        
        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if (err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });
        
//        UIManager.getInstance().setLookAndFeel(new DefaultLookAndFeel(UIManager.getInstance()) {
//            @Override
//            public void bind(Component cmp) {
//                if (cmp instanceof Container) {
//                    cmp.setScrollVisible(false);
//                }
//            }
//        });
    }
    
    public void start() {
        if (current != null) {
            current.show();
            return;
        }
        Form hi = new Form(new BorderLayout());
        
         tabs = new Tabs() {
//            @Override
//            protected Component createTab(String title, Image icon) {
//                SpanButton custom = new SpanButton(title);
//                custom.setIcon(icon);
//                custom.setUIID("Container");
//                custom.setTextUIID("Tab");
//                custom.setIconPosition(BorderLayout.NORTH);
//                custom.setIconUIID("Tab");
//                return custom;
//            }
//
//            @Override
//            protected void setTabSelectedIcon(Component tab, Image icon) {
//                ((SpanButton) tab).setPressedIcon(icon);
//            }
//
//            protected void selectTab(Component tab) {
//            }
//
//            @Override
//            protected void bindTabActionListener(Component tab, ActionListener l) {
//                ((SpanButton) tab).addActionListener(l);
//            }
        };
        // tabs.setUIID("tabs");
        tabs.setTabPlacement(BOTTOM);

//
//        Container list = new Container();
//        list.setScrollableY(true);
        //   Map<String, Object> response = (Map<String, Object>)result.get("response");
        InfiniteContainer ic = new InfiniteContainer() {
            @Override
            public Component[] fetchComponents(int index, int amount) {
                
                List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
                listMap = fetchPropertyData();
                Container[] cmps = new Container[listMap.size()];
                for (int iter = 0; iter < cmps.length; iter++) {
                    Map<String, Object> currentListing = listMap.get(iter);
                    if (currentListing == null) {
                        return null;
                    }
                    String summary = (String) currentListing.get("title");
                    String img = (String) currentListing.get("img");
                    Container content = new Container();
                    img = "http://wind.mcooz.com/data/upload/assets/" + img;
                    Label product = new Label();
                    product.setUIID("product");
                    //product.setIcon(img);
                    EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth() / 2, hi.getWidth() / 2), true);
                    URLImage background = URLImage.createToStorage(placeholder, "400px-AGameOfThrones.jpg",
                            "http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg");
                    URLImage product_img = URLImage.createToStorage(placeholder, "400px-AGameOfThrones1.jpg",
                            img);
                    Image mask = theme.getImage("arr.jpg");
                    URLImage.ImageAdapter ada = URLImage.createMaskAdapter(product_img);
                    product.setIcon(URLImage.createToStorage(placeholder, "Medium_" + iter + ".jpg", img, ada));
//                  URLImage product_img=URLImage.createToStorage(placeholder, "Medium3_.png" , img, URLImage.RESIZE_FAIL);

//                    background.fetch();
//                    Style stitle =  UIManager.getInstance().getComponentStyle("product");
//                    stitle.setBgImage(background);
                    String titleString = "3m口罩";
                    
                    Label title = new Label(summary);
                    Label price = new Label("$19.28");
                    title.setUIID("title");
                    price.setUIID("price");
                    content.setUIID("content");

//                        content.setHeight(getDisplayWidth() / 2);
//                        content.setWidth(getDisplayWidth() / 2);
                    // product.setSize(new Dimension(200,200));
                    // product.initCustomStyle(ss);
                    Container price_title = new Container();
                    price_title.add(BoxLayout.encloseY(title, price));
//                        content.add(
//                                BoxLayout.encloseY(
//                                        product,
//                                        price_title
//                                )
//                        );

                    cmps[iter] = BoxLayout.encloseX(content.add(
                            BoxLayout.encloseY(
                                    product,
                                    price_title
                            )
                    ));
                    // cmps[iter].add(content);
                }
                return cmps;
            }
        };
        
        String shoyeString = "首页";
        String cuxiaoString = "首页";
        String kaijiangString = "首页";
        String wodeString = "首页";

        //shoyeString=new InputStreamReader(shoyeString,"UTF-8");
        Button menuButton1 = new Button(shoyeString);
        Button menuButton2 = new Button(cuxiaoString);
        Button menuButton3 = new Button(kaijiangString);
        Button menuButton6 = new Button(wodeString);
        menuButton1.setUIID("z_button");
        menuButton2.setUIID("z_button");
        menuButton3.setUIID("z_button");
        menuButton6.setUIID("z_button");

        //menuButton1.setSize(new Dimension(600, 80));
        Toolbar tb1 = new Toolbar();
        GridLayout bottomGridLayout = new GridLayout(1, 4);
        tb1.setUIID("tb");

        // Container container2=FlowLayout.encloseIn( menuButton1, menuButton2, menuButton3, menuButton6);
//        Container container2=new Container();
//        container2.add(BoxLayout.encloseX(menuButton1,menuButton2,menuButton3,menuButton6));
        // container2.setLayout(bottomGridLayout);
//        tb.add(CENTER,container2);
//        tb.setHeight(30);
        //tb.setLayout(bottomGridLayout);
//        Style s1 = UIManager.getInstance().getComponentStyle("z_button");
//        FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s1);
//        Command c = tb.addMaterialCommandToRightSide("Left", icon, (e) -> Log.p("Clicked"));
//        Button b = tb.findCommandComponent(c);
        String s8 = "首页";
        String s9 = "促销";
        String s10 = "开奖";
        String s12 = "我的";
// byte[] dbbyte1 = s8.getBytes();
//System.out.println(s8);
//        
//        try {
//       //    s8=new String(dbbyte1,"iso-8859-1");
//            s8= new String(s8.getBytes("GB2312"),"ISO-8859-1");
//        } catch (Exception e) {
//        }
//  System.out.println(s8);
        ButtonGroup barGroup = new ButtonGroup();
        RadioButton all = RadioButton.createToggle(s8, theme.getImage("k.png"), barGroup);
        all.setUIID("SelectBar");
        all.setTextPosition(BOTTOM);
        RadioButton featured = RadioButton.createToggle(s9, theme.getImage("k6.png"), barGroup);
        featured.setUIID("SelectBar");
        featured.setTextPosition(BOTTOM);
        RadioButton popular = RadioButton.createToggle(s10, theme.getImage("k2.png"), barGroup);
        popular.setUIID("SelectBar");
        popular.setTextPosition(BOTTOM);
        RadioButton myFavorite = RadioButton.createToggle(s12, theme.getImage("k8.png"), barGroup);
        myFavorite.setUIID("SelectBar");
        myFavorite.setTextPosition(BOTTOM);
        Label arrow = new Label(theme.getImage("news-tab-down-arrow.png"), "Container");
        
        TableLayout tl = new TableLayout(2, 2);
        GridLayout g = new GridLayout(5, 2);
        // g.setAutoFit(true);
        ic.setLayout(g);
        ic.setUIID("ic");

        Container Cont=new Container(new BorderLayout());

        Label title_lab= new Label();

        // title_lab.setText("Home");
        // Cont.addComponent(BorderLayout.NORTH,title_lab);

        Form bs=new Form();

        bs.setTitle("home");

        bs.add(ic);

        // Cont.addComponent(BorderLayout.CENTER,ic);

       
        
//        hi.add(BorderLayout.CENTER, ic);
//        hi.add(BorderLayout.SOUTH,
//                tb1.add(CENTER, GridLayout.encloseIn(4, all, featured, popular, myFavorite)));
        try {
            ScaleImageLabel imageLabel = new ScaleImageLabel(Image.createImage("/landscape1.jpg"));
            imageLabel.setUIID("Container");
            tabs.addTab("首页", theme.getImage("k.png"), theme.getImage("k.png"), bs);
            ScaleImageLabel imageLabe2 = new ScaleImageLabel(Image.createImage("/landscape2.jpg"));
            imageLabe2.setUIID("Container");
            tabs.addTab("促销", theme.getImage("k6.png"), theme.getImage("k6.png"), new phnix());
            ScaleImageLabel imageLabe3 = new ScaleImageLabel(Image.createImage("/landscape3.jpg"));
            imageLabe3.setUIID("Container");
            tabs.addTab("开奖", theme.getImage("k2.png"), theme.getImage("k2.png"), new kaijiang());
            ScaleImageLabel imageLabe6 = new ScaleImageLabel(Image.createImage("/a.jpg"));
            imageLabe6.setUIID("Container");
            tabs.addTab("我", theme.getImage("k8.png"), theme.getImage("k8.png"), new  login_new());
            tabs.getTabsContainer().setScrollableX(false);
        } catch (IOException ex) {
            Log.e(ex);
        }
        hi.add(BorderLayout.CENTER, tabs);
  
       
        if (hiddenTabs) {
            tabs.hideTabs();
        }
        RadioButton firstTab = new RadioButton("");
        RadioButton secondTab = new RadioButton("");
        RadioButton thirdTab = new RadioButton("");
        firstTab.setEnabled(false);
        secondTab.setEnabled(false);
        thirdTab.setEnabled(false);
        
        firstTab.setUIID("Container");
        secondTab.setUIID("Container");
        thirdTab.setUIID("Container");
        new ButtonGroup(firstTab, secondTab, thirdTab);
        firstTab.setSelected(true);
        tabsFlow = FlowLayout.encloseCenter(firstTab, secondTab, thirdTab);
        hi.add(BorderLayout.SOUTH, tabsFlow);
        tabsFlow.setHidden(!hiddenTabs);
        tabs.addSelectionListener((i1, i2) -> {
            switch (i2) {
                case 0:
                    if (!firstTab.isSelected()) {
                        firstTab.setSelected(true);
                       
                    }
                    break;
                case 1:
                    if (!secondTab.isSelected()) {
                        secondTab.setSelected(true);
                    }
                    break;
                case 2:
                    if (!thirdTab.isSelected()) {
                        thirdTab.setSelected(true);
                    }
                    break;
            }
        });
        System.out.println(tabs.getComponentIndex(all));       
       
        
//         new login_new().gui_Button.addActionListener(e -> {
//             System.out.println(123);
//        });
         
        ic.setScrollVisible(hiddenTabs);
        hi.getToolbar().hideToolbar();
        hi.show();
    }
    int pageNumber = 1;
    
    java.util.List<Map<String, Object>> fetchPropertyData() {
        try {
            ConnectionRequest r = new ConnectionRequest();
            r.setUrl("http://wind.mcooz.com/index/ajax_index");
            pageNumber++;
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map<String, Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            return (java.util.List<Map<String, Object>>) result.get("products");
        } catch (Exception err) {
            Log.e(err);
            return null;
        }
        
    }
    

  
    
    public void stop() {
        current = getCurrentForm();
        if (current instanceof Dialog) {
            ((Dialog) current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }
    
    public  void hid(){
        
       tabsFlow.setHidden(true);
    }
    
        public void show_user(){      

       tabs.removeTabAt(3);
       tabs.addTab("我", theme.getImage("k8.png"), theme.getImage("k8.png"), new user());
       tabs.setSelectedIndex(3);

    }
    
}
